package com.hxy.platform.admin.controller;

import com.hxy.platform.admin.pojo.Blog;
import com.hxy.platform.admin.service.BlogService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class BlogController {
    @Autowired
    private BlogService blogService;

    /**
     * 跳转到文章管理界面
     *
     * @return
     */
    @RequestMapping("page/articleList")
    public String articleList(ModelMap modelMap) {
        List<Blog> blogs = blogService.getAll();
        modelMap.addAttribute("blogs", blogs);
        return "articleList";
    }

    /**
     * 跳转到编辑文章界面
     */
    @RequestMapping("page/articleDetail")
    public String articleDetail(@RequestParam("id") Integer id, ModelMap modelMap, Blog oldBlog) {
        if (StringUtils.isBlank(oldBlog.getAuthor())) {
            Blog blog = blogService.getById(id);
            modelMap.addAttribute("blog", blog);
            return "updateArticle";
        }
        int result = blogService.updateArticle(oldBlog);
        if (result > 0) {
            List<Blog> blogs = blogService.getAll();
            modelMap.addAttribute("blogs", blogs);
            return "articleList";
        }
        return "";
    }

    /**
     * 跳转到添加文章界面
     */
    @RequestMapping("page/addArticle")
    public String addArticle(Blog blog, ModelMap modelMap) {
        if (StringUtils.isBlank(blog.getAuthor())) {
            return "addArticle";
        }
        int result = blogService.addArticle(blog);
        if (result > 0) {
            List<Blog> blogs = blogService.getAll();
            modelMap.addAttribute("blogs", blogs);
            return "articleList";
        }
        return "";
    }
    /**
     * 删除文章
     */
    @RequestMapping("article/deleteById")
    public String deleteById(@RequestParam("id") Integer id, ModelMap modelMap) {
        blogService.deleteById(id);
        List<Blog> blogs = blogService.getAll();
        modelMap.addAttribute("blogs", blogs);
        return "articleList";
    }

}
